package app.quiz;

import app.quiz.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 8/10/12
 * Time: 3:45 PM
 */
public class QuizServlet extends GenericPatternServlet {

    private List<String> questions;
    private String username;


    @Override
    public void init() throws ServletException {

        super.init();

        initQuestions();
    }


    @Override
    protected void setHtmlFileName() {
        htmlFileName = "quizTemplate.html";
    }

    @Override
    protected void fillInHTMLTemplate(HttpServletRequest request, HttpServletResponse response) {

        String question = questions.get(HomeServlet.questionIndex);
        HomeServlet.questionIndex++;

        htmlTemplate.reset();
        htmlTemplate.setAttribute(Constants.QUESTION, question);
        htmlTemplate.setAttribute(Constants.USERNAME, username);

    }

    @Override
    protected boolean doSomeInitialProcessing(HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (validateLoginInfo(request, response)) return false;

        processLoginInfo(request, response);

        return processAnswer(request, response);
    }


    private boolean validateLoginInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (isNotValidLogin(request)) {
            HomeServlet.resultMessage = Constants.LOGIN_ERROR_MESSAGE;
            response.sendError(414);
            return true;
        }
        return false;
    }

    private boolean processAnswer(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String answer = request.getParameter(Constants.ANSWER);

        HomeServlet.score += (answer != null && answer.length() > 0) ? Integer.valueOf(answer) : 0;

        if (HomeServlet.questionIndex >= Constants.maxQuestions || HomeServlet.elapsedTime <= 0) {
            setResultMessage();
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + Constants.resultServletPath));
            return false;
        }

        return true;
    }

    private void processLoginInfo(HttpServletRequest request, HttpServletResponse response) {
        if (atFirstQuestion()) {

            setUsername(request);

            if(rememberMe(request)) addLoginCookies(request, response);
        }
    }

    private boolean rememberMe(HttpServletRequest request) {
        return request.getParameter("remember")!=null;
    }

    private boolean atFirstQuestion() {
        return HomeServlet.questionIndex == 0;
    }


    private void addLoginCookies(HttpServletRequest request, HttpServletResponse response) {

        String username = request.getParameter(Constants.USERNAME), password = request.getParameter(Constants.PASSWORD);

        if (username == null || password == null)
            return;

        Cookie usernameCookie = new Cookie(Constants.USERNAME, username), passwordCookie = new Cookie(Constants.PASSWORD, password);

        usernameCookie.setDomain(Constants.EMPTY_STRING);
        usernameCookie.setPath(Constants.cookiePath);
        usernameCookie.setMaxAge(Constants.EXPIRY_TIME);

        passwordCookie.setDomain(Constants.EMPTY_STRING);
        passwordCookie.setPath(Constants.cookiePath);
        passwordCookie.setMaxAge(Constants.EXPIRY_TIME);


        response.addCookie(usernameCookie);
        response.addCookie(passwordCookie);

    }

    private void setUsername(HttpServletRequest request) {

        username = request.getParameter(Constants.USERNAME);

    }


    private void initQuestions() {

        questions = new ArrayList<String>();
        questions.add("Do you like Paris?");
        questions.add("Is your city really crowded?");
        questions.add("Do you plan on going on a holiday anytime soon?");

    }

    private void setResultMessage() {

        if (HomeServlet.elapsedTime <= 0)
            HomeServlet.resultMessage = Constants.timeExpiredMessage;
        else
            HomeServlet.resultMessage = (HomeServlet.score > Constants.mediumScore) ? Constants.winMessage : Constants.loseMessage;
    }


    private boolean isNotValidLogin(HttpServletRequest request) {

        String username = request.getParameter(Constants.USERNAME), password = request.getParameter(Constants.PASSWORD);

        return username != null && password != null && (username.equals(Constants.EMPTY_STRING) || password.equals(Constants.EMPTY_STRING));
    }
}
